package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.web.core.business.dto.GroupRequest;
import com.jiyinit.web.core.business.dto.MChatRequest;
import com.jiyinit.web.core.business.entity.TabCoreGroupEntity;
import com.jiyinit.web.core.business.entity.TabUserGroupEntity;
import com.jiyinit.web.core.business.enums.CommonEnum;
import com.jiyinit.web.core.business.service.GroupServiceImpl;
import com.jiyinit.web.core.business.service.UserGroupServiceImpl;
import com.jiyinit.web.core.business.vo.GroupMemberVo;
import com.jiyinit.web.core.business.vo.GroupVo;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by changly on 2017/12/6.
 */
@Controller
@RequestMapping("/mobile/group")
public class MgroupController {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MgroupController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.groupService")
    private GroupServiceImpl groupServiceImpl;

    @Resource(name = "core.userGroupServiceImpl")
    private UserGroupServiceImpl userGroupService;

    /**
     * 新建群组
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value ="addGroup")
    public ResponseEntity<ResponseDto> addGroup(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/group/addGroup");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        GroupRequest groupRequest = (GroupRequest) JsonEntityTransform.json2Object(logJson, GroupRequest.class);
        // 校验参数
        ValidateResult<GroupRequest> validateResult = paramCheckLogic.checkParamValidate(groupRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        if(groupRequest.getUserId() == null) {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("创建者ID不能为空"),HttpStatus.OK);
        }
        if(groupRequest.getGroupName() == null || ("").equals(groupRequest.getGroupName())) {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("群名称不能为空"),HttpStatus.OK);
        }

        //创建群
        int groupId = groupServiceImpl.addGroup(groupRequest);
        //通知即时通讯项目，添加的群成员
        HashMap<String,String> param = new HashMap<>();
        param.put("appId", "1");
        param.put("groupId",String.valueOf(groupId));
        param.put("userIds","");
        param.put("identity", CommonEnum.Identity.HAREN.getCode().toString());
        param.put("createId",groupRequest.getUserId().toString());
        param.put("lastModifyId","");
        param.put("groupName",groupRequest.getGroupName());
        String path = (String) PropertyPlaceholderConfigurer.getContextProperty("IM_URL");
        String paramsStr = JsonEntityTransform.object2Json(param);
        /*MChatRequest messageRequest = this.getJsonToRequest(request);
        Map<String, String> headers=new HashMap<String, String>();
        headers.put("token",messageRequest.getToken());
        headers.put("sign",messageRequest.getSign());*/
        String result =  HttpClientUtil.post(path+"/group/saveGroupUserInfo",paramsStr,null);
        if(groupId > 0){
            LogUtil.info(LOGGER, "接口:/mobile/group/addGroup,返回结果{}", JsonEntityTransform.object2Json(groupId));
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(groupId),HttpStatus.OK);
        }
        LogUtil.info(LOGGER, "接口:/mobile/group/addGroup,返回结果{}", JsonEntityTransform.object2Json(groupId));
        return  new ResponseEntity<ResponseDto>(ResponseDto.responseFail("创建群组失败"),HttpStatus.OK);
    }

    /**
     * 群组添加人员
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value ="/addMember")
    public ResponseEntity<ResponseDto> addMember(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/group/addMember");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        GroupRequest groupRequest = (GroupRequest) JsonEntityTransform.json2Object(logJson, GroupRequest.class);
        if(groupRequest.getGroupId() == null) {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("群组ID不能为空"),HttpStatus.OK);
        }
        if(groupRequest.getUserIds() == null || ("").equals(groupRequest.getUserIds())) {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("用户ID不能为空"),HttpStatus.OK);
        }
        String[] userIds = groupRequest.getUserIds().split(",");

        Integer[] params = new Integer[userIds.length];
        for(int i=0;i<userIds.length;i++){
            params[i] = new Integer(userIds[i]);
        }
        //防止用户重复添加到同一个群组中
        List<TabUserGroupEntity> groupMember = userGroupService.findGroupMemberByGroupId(groupRequest.getGroupId());
        for(int i=0;i<userIds.length;i++){
            params[i] = new Integer(userIds[i]);
            for(TabUserGroupEntity entity :groupMember){
                if(entity.getUserId().intValue() == params[i].intValue()){
                    return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("用户("+entity.getUserName()+")在此群中已存在"),HttpStatus.OK);
                }
            }
        }

        //添加人员
        int num = userGroupService.addUsers(groupRequest.getGroupId(),params,groupRequest.getUserId());

        //通知即时通讯项目，添加的群成员
        HashMap<String,String> param = new HashMap<>();
        param.put("appId", "1");
        param.put("groupId",groupRequest.getGroupId().toString());
        param.put("userIds",groupRequest.getUserIds());
        param.put("identity", CommonEnum.Identity.GENGERAL.getCode().toString());
        param.put("createId",groupRequest.getUserId().toString());
        param.put("lastModifyId","");
        String path = (String) PropertyPlaceholderConfigurer.getContextProperty("IM_URL");
        String paramsStr = JsonEntityTransform.object2Json(param);
        String result =  HttpClientUtil.post(path+"/group/saveGroupUserInfo",paramsStr,null);

        if(num > 0){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(""),HttpStatus.OK);
        }
        return  new ResponseEntity<ResponseDto>(ResponseDto.responseFail("创建群组失败"),HttpStatus.OK);
    }
    //查找群组人员
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value ="/findGroupMember")
    public ResponseEntity<ResponseDto> findGroupMember(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/group/findGroupMember");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        GroupRequest groupRequest = (GroupRequest) JsonEntityTransform.json2Object(logJson, GroupRequest.class);
        List<TabCoreGroupEntity> list = userGroupService.findGroup(groupRequest.getUserId());
        HashMap<Integer,List<GroupMemberVo>> vo = userGroupService.findGroupMember(groupRequest.getUserId());

//        HashMap result = new HashMap();
//        result.put("group",list);
//        result.put("meber",vo);
        List<GroupVo> result =new  ArrayList();
        for (TabCoreGroupEntity entity : list){
            GroupVo groupvo  = new GroupVo();
            BeanUtils.copyProperties(entity,groupvo);
            if(vo.get(entity.getGroupId()) != null) groupvo.setMeber(vo.get(entity.getGroupId()));
            result.add(groupvo);
        }

      if(vo == null){
          return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("查询失败"),HttpStatus.OK);
      }
        LogUtil.info(LOGGER, "接口:/mobile/group/findGroupMember,返回结果{}", JsonEntityTransform.object2Json(result));
        return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(result),HttpStatus.OK);
    }

    /**
     * 解散群
     * @author liuzongguang
     * @create 2018/8/21 15:23
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/dissolveGroup")
    public ResponseEntity<ResponseDto> dissolveGroup(HttpServletRequest request)
    {
        LogUtil.info(LOGGER, "接口:{}", "/mobile/group/addGroup");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        GroupRequest groupRequest = JsonEntityTransform.json2Object(logJson, GroupRequest.class);
        // 校验参数
        ValidateResult<GroupRequest> validateResult = paramCheckLogic.checkParamValidate(groupRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        if(groupRequest.getUserId() == null) {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("用户ID不能为空"),HttpStatus.OK);
        }
        if(groupRequest.getGroupId()==null)
        {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("组编ID不能为空"),HttpStatus.OK);
        }

        TabCoreGroupEntity entity=groupServiceImpl.selectByPrimaryKey(groupRequest.getGroupId());
        if(!String.valueOf(groupRequest.getUserId()).equals(String.valueOf(entity.getCreateId())))
        {
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("群创建者才能解散该群"),HttpStatus.OK);
        }
        boolean result = groupServiceImpl.dissolveGroup(groupRequest.getGroupId());

        if(result){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK("解散群成功"),HttpStatus.OK);
        }
        return  new ResponseEntity<ResponseDto>(ResponseDto.responseFail("解散群失败"),HttpStatus.OK);
    }

    /**
     * 群组删除人员
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value ="/delUser")
    public ResponseEntity<ResponseDto> delMember(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/group/delUser");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        GroupRequest groupRequest = (GroupRequest) JsonEntityTransform.json2Object(logJson, GroupRequest.class);

        TabCoreGroupEntity entity=groupServiceImpl.selectByPrimaryKey(groupRequest.getGroupId());
        int createId = entity.getCreateId();//群主id

        if(groupRequest.getRemoveUserId().intValue() == createId
                && groupRequest.getUserId().intValue() == createId){//如果群主要移除自己的话, 不允许
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("你是群主, 不可以移除自己, 如果要移除, 请解散此群!"),HttpStatus.OK);
        }
        if(groupRequest.getRemoveUserId().intValue() == createId
                && groupRequest.getUserId().intValue() != createId){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("你不可以移除群主!"),HttpStatus.OK);
        }
        if(groupRequest.getUserId().intValue() != createId
                && groupRequest.getRemoveUserId().intValue() != groupRequest.getUserId().intValue()){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("只有群主可以进行此操作!"),HttpStatus.OK);
        }

        TabUserGroupEntity userGroupEntity=new TabUserGroupEntity();
        userGroupEntity.setUserId(groupRequest.getRemoveUserId());
        userGroupEntity.setGroupId(groupRequest.getGroupId());
        //删除人员
        int num = userGroupService.delUsers(userGroupEntity);

        if(num > 0){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(""),HttpStatus.OK);
        }
        return  new ResponseEntity<ResponseDto>(ResponseDto.responseFail("删除失败"),HttpStatus.OK);
    }

    private MChatRequest getJsonToRequest(HttpServletRequest request){
        String logJson = request.getParameter("request_json");
        MChatRequest taskRequest=JsonEntityTransform.json2Object(logJson, MChatRequest.class);
        return taskRequest;
    }

}
